import 'package:dio/dio.dart';
import '../utils/storage_util.dart';
import './http_client.dart'; // 通用 HTTP 客户端封装

class AuthService {
  final HttpClient _httpClient = HttpClient();

  /// 登录（通过手机号和验证码）
  Future<bool> login(String phone, String code) async {
    final responseData = await _httpClient.post(
      '/auth/loginBySms',
      data: {
        'phone': phone,
        'code': code,
      },
    );
    if (responseData['data']['access_token'] != null) {
      final token = responseData['data']['access_token'];

      // 检查是否有过期时间信息
      Duration? expiryDuration;
      if (responseData['data']['expires_in'] != null) {
        final expiresIn = responseData['data']['expires_in'] as int;
        expiryDuration = Duration(seconds: expiresIn);
      }

      await _httpClient.saveToken(token); // 保存到HttpClient
      await StorageUtil.saveToken(token,
          expiryDuration: expiryDuration); // 保存到StorageUtil
      return true;
    } else {
      return false;
    }
  }

  /// 获取验证码（通过手机号）
  Future<String> getSmsCode(String phone) async {
    try {
      final result = await _httpClient.get(
        '/auth/smsCode',
        queryParameters: {'phone': phone},
      );
      // 兼容后端返回格式
      if (result is Map && result['code'] == 200 && result['data'] is String) {
        return result['data'];
      } else if (result is String) {
        return result;
      } else {
        throw '验证码返回格式错误';
      }
    } on DioException catch (e) {
      rethrow;
    }
  }

  /// 获取当前用户信息（需登录态）
  Future<Map<String, dynamic>> getUserInfo() async {
    try {
      final result = await _httpClient.get('/system/user/getInfo');
      return result;
    } on DioException catch (e) {
      if (e.response?.statusCode == 401) {
        // 可添加自动跳转登录逻辑等
      }
      rethrow;
    }
  }

  /// 退出登录（清除本地 Token）
  Future<void> logout() async {
    try {
      await _httpClient.delete('/auth/logout');
    } catch (e) {
    }

    await _httpClient.clearToken();
    await StorageUtil.clearToken();
  }
}
